<script setup>
import { ref,onMounted,nextTick,reactive,inject,computed } from 'vue'
import Folder from '@/components/Folder.vue'
import Organization from '@/components/Organization.vue'
import { userStateStore } from '@/stores/userState'

//状态状态，全局响应数据
const userState = userStateStore();
//全局方法
const global = inject('global');

function getImageUrl(name) {
  return import.meta.env.BASE_URL+name;
}

//注册APP应用
const apps = reactive({
    organization:{
        open:false
    },
    folder:{
        open:false,
        icon:new URL('@/assets/images/folder-sm.png', import.meta.url).href,
        title:'作业目录'
    },
    viewPicture:{
        open:false,
        icon:new URL('@/assets/images/pics.png', import.meta.url).href,
    },
    codedFile:{
        icon:new URL('@/assets/images/notepad.png', import.meta.url).href,
        open:false
    },
    vidSm:{
        open:false,
    },
    yuanshen:{
        open:false
    }
});

//Source code address

//当前打开的APP应用
const currentActivityApp = ref('');

const windowIcon = ref(new URL('@/assets/images/home.png', import.meta.url).href);
//作业文件路径
const taskFolderPath = ref([]);
//作业文件域名
const taskFolderUrl = ref('');
//作业文件，代码模式的代码
const taskFolderFileCode = ref('');
//代码类型
const codeType = ref('javascript');

//获取当前页面的dom元素
const appsDom = ref();

//图片窗口的图片地址
const viewPictureStr = ref('');

//桌面上显示的图标
const desktopIcon = ref([
    {
        'icon':new URL('@/assets/images/user.png', import.meta.url).href,
        'name':'我的班级',
        'id':'organization',
    },
    {
        'icon':new URL('@/assets/images/bin0.png', import.meta.url).href,
        'name':'回收站',
        'id':'recycle',
    },
    {
        'icon':new URL('@/assets/images/github.png', import.meta.url).href,
        'name':'源码地址',
        'id':'sourceCode',
        height:800,
        width:1200
    },
    {
        'icon':new URL('@/assets/images/vid-sm.png', import.meta.url).href,
        'name':'西瓜视频',
        'id':'vidSm',
        height:600,
        width:800
    },
    {
        'icon':new URL('@/assets/images/a.jpg', import.meta.url).href,
        'name':'原神启动',
        'id':'yuanshen',
        height:800,
        width:1200
    }

    
]);


//计算属性
const openApplength = computed(()=>{
    let i = 0;
    for(let key in apps){
        if(apps[key].open){
            i++
        }
    }
    return i;
});

//当窗口点击更改zindex的事后执行。更新nav的高亮
function appMoveToTop(dom){
    currentActivityApp.value = dom.attr('aria-describedby');
}

//当窗口关闭的时候。更新nav的高亮
function appCloseActivityApp(){

    let maxZindex = {v:0,dom:null};
    $('[role="dialog"]').map(function (){
        if(maxZindex.v <= $(this).css('z-index')){
            maxZindex.v = $(this).css('z-index');
            maxZindex.dom = this;
        }
    })

    if(maxZindex.dom)currentActivityApp.value = $(maxZindex.dom).attr('aria-describedby');
}

function navAppClick(appID){
    let maxZindex = {v:0,dom:null};
    $('[role="dialog"]').map(function (){
        if(maxZindex.v <= $(this).css('z-index')){
            maxZindex.v = $(this).css('z-index');
            maxZindex.dom = this;
        }
    })
    $(`[aria-describedby=${appID}]`).css('z-index',maxZindex.v*1+1);
    currentActivityApp.value = appID;
}

//打开单个文件应用
function openFileWindow(key){
    
    let type = key.split('.')[1]
    if(type == 'png' || type == 'jpg' || type == 'jpeg' || type == 'webp'){
        openViewPicture(key);
    }else{
        openCodedFile(key);
    }
    
}

//打开一张图片
function openViewPicture(key){
    apps.viewPicture.open = true;
    apps.viewPicture.title = key.split('/')[key.split('/').length -1];
    
    viewPictureStr.value = taskFolderUrl.value+key

    nextTick(()=>{
        let dom = $(`#viewPicture`);
        $(dom).dialog({
            width:800,
            height:800,
            appMoveToTop,
            close:function (){
                apps['viewPicture'].open = false;
                $(this).eq(0).parent().remove();
                appCloseActivityApp();
            }
        });
    })
    
}

//打开代码模式
function openCodedFile(key){

    global.axios.get(taskFolderUrl.value+key) // 将URL替换为目标网页地址
    .then(function (response) {
        taskFolderFileCode.value = response.data;
    })
    .catch(function (error) {
        console.log(error);
    });

    apps.codedFile.open = true;
    let type = 'javascript';
    switch (key.split('.')[key.split('.').length-1]){
        case 'html':
        type = 'html'
        break;
        case 'css':
        type = 'css'
        break;
        case 'js':
        type = 'javascript'
        break;
    }
    codeType.value = type

    apps.codedFile.title = key.split('/')[key.split('/').length -1];

    nextTick(()=>{
        let dom = $(`#codedFile`);
        $(dom).attr('icon',new URL('@/assets/images/notepad.png', import.meta.url).href);
        
        
        $(dom).dialog({
            width:800,
            height:800,
            appMoveToTop,
            close:function (){
                apps['codedFile'].open = false;
                $(this).eq(0).parent().remove();
                appCloseActivityApp();
            }
        });

        setTimeout(()=>{
            $('[aria-describedby="codedFile"] .ui-dialog-title .text').html(apps.codedFile.title);
            hljs.initHighlightingOnLoad()
        },1);
    })
    
}

//打开桌面应用
function openApp(item){
    if(item.id == 'sourceCode'){
        window.open("https://gitee.com/bbfjj/web-window11")
        return false;
    }
    //https://gitee.com/bbfjj/web-window11
    if(!apps[item.id]){
        global.prompt('功能暂未开放');
        return false;
    }

    currentActivityApp.value = item.id;
    apps[item.id].open = true;
    apps[item.id].title = item.name;
    apps[item.id].icon = item.icon;

    nextTick(()=>{
        let dom = appsDom.value.querySelector(`#${item.id}`);
        $(dom).attr('title',item.name);
        $(dom).attr('icon',item.icon);

        $(dom).dialog({
            width:item.width || 900,
            height:item.height || 500,
            appMoveToTop,
            close:function (){

                apps[item.id].open = false;
                $(this).eq(0).parent().remove()
                
                item = null;
                appCloseActivityApp();
            }
        });
        $( ".selectable" ).selectable();
        $( ".ww" ).draggable({ opacity: 0.7, helper: "clone" });
        //$( $(dom)).resizable();

    })
}

//打开作业系统
function openTaskFolder(data){

    
    currentActivityApp.value = 'folder';


    let organization = userState.user.organization;
    let _a = '';
    let _b = '';
    let _c = '';
    
    for(let key in organization){
        _a = organization[key].id;
        _b = organization[key].organization_class_id;
        for(let key2 in organization[key].task){
            if(organization[key].task[key2].id == data.id){

                _c = organization[key].task[key2].id;
            }
        }
    }
    global.axiosToken({
        method: 'post',
        url: `/api/users/getTaskFolder`,
        data: {
            organization:_a,
            organization_class:_b,
            organization_user_task:_c
        }
    }).then(function (response) {
        if(response.data.code){
            taskFolderPath.value = response.data.data.dir
            taskFolderUrl.value  = response.data.data.path
            apps.folder.open = true;
            apps.folder.title = data.name;
            nextTick(()=>{
                nextTick(()=>{
                    let dom = appsDom.value.querySelector(`#folder`);

                    $(dom).dialog({
                        width:1200,
                        height:700,
                        appMoveToTop,
                        close:function (){
                            apps['folder'].open = false;
                            $(this).eq(0).parent().remove();
                            appCloseActivityApp();
                        }
                    });
                    $( ".selectable" ).selectable();
                    $( ".ww" ).draggable({ opacity: 0.7, helper: "clone" });

                })
            })

        }
    }).catch(function (error) {
        console.log(error);
    });

}

onMounted(() => {
    $( ".window" ).selectable();
})


</script>
<template>
    <div class="windowBg">
        <div class="window">
            <div class="desktopIconWrap">
                <template  v-for="(item,index) in desktopIcon">
                    <div class="desktopIcon" @click="openApp(item,index)">
                        <div class="img" :style="`background-image:url('${item.icon}');`"></div>
                        <div class="name">{{item.name}}</div>
                    </div>
                </template>
            </div>
            <div ref="appsDom" id="appsDomWrap">

                <Organization v-if="apps['organization'].open" id="organization" :openTaskFolder="openTaskFolder" ></Organization>
                <Folder  v-if="apps['folder'].open"  id="folder" :taskFolderPath="taskFolderPath" :openFileWindow="openFileWindow" :title="apps['folder'].title" :icon="apps['folder'].icon"></Folder>
                
                <div id="viewPicture" v-if="apps['viewPicture'].open"  :icon="apps['viewPicture'].icon" :title="apps['viewPicture'].title">
                    <div class="viewPictureImage">
                        <img :src="viewPictureStr"/>
                    </div>
                </div>
                
                <div class="codedFile txtSelect" id="codedFile" v-if="apps['codedFile'].open">
                    <pre><code id="mycode" :class="codeType">{{taskFolderFileCode}}</code></pre>
                </div>
                
                <div id="vidSm" v-if="apps['vidSm'].open">
                    <iframe :src="getImageUrl('video')"  scrolling="no"></iframe>
                </div>

                <div id="yuanshen" v-if="apps['yuanshen'].open">
                    <iframe src="https://ys.fancyb.top/"  scrolling="no"></iframe>
                </div>
            </div>

            
            <nav>
                <div class="left">
                    <div class="app desktopIcon">
                        <div class="img" :style="`background-image: url('${windowIcon}')`"></div>
                    </div>
                </div>
                <div class="main">
                    <template v-for="(item,key) in apps">
                        <div :class="'app desktopIcon '+`${currentActivityApp == key?'currentActivityApp':''}`" v-if="item.open" @click="navAppClick(key)">
                            <div class="img" :style="`background-image: url(${item.icon})`"></div>
                            <div class="title">{{item.title}}</div>
                        </div>
                    </template>
                </div>
            </nav>
        </div>
    </div>
</template>


<style lang="scss" >
.hljs-comment,.hljs-quote{color:#999}.hljs-deletion,.hljs-name,.hljs-regexp,.hljs-selector-class,.hljs-selector-id,.hljs-tag,.hljs-template-variable,.hljs-variable{color:#f2777a}.hljs-built_in,.hljs-builtin-name,.hljs-link,.hljs-literal,.hljs-meta,.hljs-number,.hljs-params,.hljs-type{color:#f99157}.hljs-attribute{color:#fc6}.hljs-addition,.hljs-bullet,.hljs-string,.hljs-symbol{color:#9c9}.hljs-section,.hljs-title{color:#69c}.hljs-keyword,.hljs-selector-tag{color:#c9c}.hljs{display:block;overflow-x:auto;background:#2d2d2d;color:#ccc;padding:.5em}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}


#codedFile{ display: flex; flex-direction: column;
    align-items:stretch; 
    justify-content: center;
}
#codedFile pre{flex: 1; background-color: #2d2d2d; display: flex; flex-direction: column;
    align-items:stretch; 
    justify-content: center;}
#codedFile code{flex: 1; white-space:nomal}


nav{ display:flex;}
nav .app{ position: relative; padding: 3px 0; height: 28px; margin:8px 3px;  display:flex; align-items:center; width: 38px; border: none; }
nav .app:hover{ background-color: rgba(255,255,255,0.7); border: none;}
nav .app:hover .title{ opacity: 0.8;}
nav .app .title{ color:#fff;  border-radius: 2px; position:absolute; font-size: 12px; top: -30px; width: 80px; padding: 2px 0 ; margin-left: -40px; left:50%; text-align: center; opacity: 0;}
nav .app .img{ width:22px; height:22px; flex:1; background-size:contain; background-repeat: no-repeat;  }

nav .currentActivityApp{ background-color: rgba(255,255,255,0.7);}

nav .left{ width: 70px; padding-left: 10px; }
nav .main{ display:flex;   flex:1;}

#viewPicture{ position: relative; display:flex; justify-content:center;   align-items:center; }
.viewPictureImage{flex:1; }


#vidSm{ position: relative; overflow: hidden;}
iframe{ position:absolute; width: 100%; height: 100%; border: none;}
</style>

